package com.ruijie.autotest.log.common.sql;

import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class SqlTable {

	private static final String DESC_COLUMN_TYPE = "Type";

	private static final String DESC_COLUMN_FIELD = "Field";

	private final DataSource dataSource;

	private final String tableName;

	public SqlTable(DataSource dataSource, String tableName) {
		this.dataSource = dataSource;
		this.tableName = tableName;
	}

	public List<SqlField> columnFields() {
		List<SqlField> result = new ArrayList<>();
		List<String> fieldNames = descResultOf(DESC_COLUMN_FIELD);
		List<String> types = descResultOf(DESC_COLUMN_TYPE);
		for (int at = 0; at < fieldNames.size(); at++) {
			result.add(new SqlField(dataSource, tableName, fieldNames.get(at), new SqlType(types.get(at))));
		}
		return result;
	}

	public SqlField columnFieldOf(String fieldName) {
		// TODO 2021/1/6 memory usage here might be too heavy.
		return columnFields().stream()
				.filter(sqlField -> sqlField.fieldName().equals(fieldName))
				.findFirst().orElseThrow(() -> new RuntimeException("fieldName: " + fieldName + " doesn't exists."));
	}

	private List<String> descResultOf(String columnLabel) {
		List<String> result = new ArrayList<>();
		try (Connection connection = dataSource.getConnection();
		     Statement statement = connection.createStatement()) {
			ResultSet rows = statement.executeQuery("desc " + tableName);
			while (rows.next()) {
				// each row
				result.add(rows.getString(columnLabel));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return result;
	}
}
